package com.wans.utils.string;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 随机字符串
 */
public class RandomStringUtils {

    // 定义所有可用字符（小写字母+大写字母+数字）
    private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成指定长度的随机字符串（包含大小写字母和数字）
     *
     * @param length 生成的字符串长度
     * @return 随机字符串
     * @throws IllegalArgumentException 如果长度小于等于0
     */
    public static String random(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从可用字符集中随机选取一个字符
            int randomIndex = RANDOM.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(randomIndex));
        }
        return sb.toString();
    }

    /**
     * 生成排除易混淆字符的随机字符串
     *
     * @param length 生成的字符串长度
     * @return 排除易混淆字符的随机字符串
     */
    public static String randomExcludeAmbiguous(int length) {
        // 排除0/O/o、1/I/l 等易混淆字符
        String SAFE_CHARACTERS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
        return generateFrom(length, SAFE_CHARACTERS);
    }

    /**
     * 生成指定字符集的随机字符串
     *
     * @param length 生成的字符串长度
     * @param charPool 字符池
     * @return 基于指定字符池的随机字符串
     */
    private static String generateFrom(int length, String charPool) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0");
        }
        if (charPool == null || charPool.isEmpty()) {
            throw new IllegalArgumentException("字符池不能为空");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = RANDOM.nextInt(charPool.length());
            sb.append(charPool.charAt(randomIndex));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // 基本用法
        System.out.println("8位随机字符串: " + random(8));
        System.out.println("12位随机字符串: " + random(12));

        // 增强功能
        System.out.println("排除易混淆字符: " + randomExcludeAmbiguous(10));
    }
}
